package forms;

import models.LoginModel;
import java.awt.Toolkit;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

public class Login extends javax.swing.JFrame {

    private String username;
    private String password;
    String sql;
    ResultSet rs;
    Connection connection = null;
    boolean check;
    LoginModel db;

    public Login() {
        initComponents();
        LoginModel db = new LoginModel();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        txt_password = new javax.swing.JPasswordField();
        sms = new javax.swing.JLabel();
        remember = new javax.swing.JCheckBox();
        txt_username = new javax.swing.JTextField();
        btn_login = new javax.swing.JButton();
        btn_cancel = new javax.swing.JButton();
        background = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);

        jPanel1.setMaximumSize(new java.awt.Dimension(600, 350));
        jPanel1.setMinimumSize(new java.awt.Dimension(600, 350));
        jPanel1.setPreferredSize(new java.awt.Dimension(598, 350));
        jPanel1.setLayout(null);

        txt_password.setColumns(2);
        txt_password.setFont(new java.awt.Font("Times New Roman", 0, 24)); // NOI18N
        txt_password.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));
        jPanel1.add(txt_password);
        txt_password.setBounds(200, 145, 340, 40);

        sms.setFont(new java.awt.Font("Tahoma", 3, 18)); // NOI18N
        sms.setForeground(new java.awt.Color(255, 0, 0));
        jPanel1.add(sms);
        sms.setBounds(240, 190, 300, 30);

        remember.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        remember.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rememberActionPerformed(evt);
            }
        });
        jPanel1.add(remember);
        remember.setBounds(200, 200, 20, 20);

        txt_username.setColumns(1);
        txt_username.setFont(new java.awt.Font("Times New Roman", 0, 24)); // NOI18N
        txt_username.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));
        txt_username.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                txt_usernameMouseEntered(evt);
            }
        });
        txt_username.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txt_usernameActionPerformed(evt);
            }
        });
        jPanel1.add(txt_username);
        txt_username.setBounds(200, 88, 340, 40);
        txt_username.getAccessibleContext().setAccessibleName("");
        txt_username.getAccessibleContext().setAccessibleDescription("");

        btn_login.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/lgin_btn.png"))); // NOI18N
        btn_login.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        btn_login.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_loginActionPerformed(evt);
            }
        });
        jPanel1.add(btn_login);
        btn_login.setBounds(200, 240, 150, 40);

        btn_cancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/cancel_btn.png"))); // NOI18N
        btn_cancel.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        btn_cancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_cancelActionPerformed(evt);
            }
        });
        jPanel1.add(btn_cancel);
        btn_cancel.setBounds(390, 240, 150, 40);

        background.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/form_login.png"))); // NOI18N
        background.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        background.setDebugGraphicsOptions(javax.swing.DebugGraphics.FLASH_OPTION);
        jPanel1.add(background);
        background.setBounds(0, 0, 600, 330);
        background.getAccessibleContext().setAccessibleDescription("");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 600, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 330, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        jPanel1.getAccessibleContext().setAccessibleName("");

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void btn_loginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_loginActionPerformed
        username = this.txt_username.getText().trim();
        password = this.txt_password.getText().trim();
        if (!username.equals("")) {
            if (!password.equals("")) {
                db = new LoginModel();
                sql = "SELECT * FROM users where use_username='" + username + "'";
                rs = db.select(sql);
                
                try {
                    if (rs.next()) { //compare username
                        sql = "SELECT * FROM users where use_username='" + username + "' && use_password=md5('" + password + "')";
                        rs = db.select(sql);
                        if (rs.next()) {
                            POS_Panel panel = new POS_Panel();
                            panel.setVisible(true);
                            String use_role = rs.getString("use_groupid");
                            this.close();
                            Login login = new Login();
                            this.unlockUser();//delete file incorrect password file
                            if (check == true) {
                                this.writeFile("remember", rs.getString("use_password"));//writeFile("Filename","text to be written");
                            }
                        } else {
                            String readfile = "";
                            readfile = this.readFile("incorrect_password");//readFile(String filename) is a static method to read file                     
                            this.writeFile("incorrect_password", "1" + readfile);//writeFile(String filename,String text) is a static method to write file
                            if (readfile.equals("1111")) {
                                this.disable_all_buttons();
                                db.close();
                            } else {
                                JOptionPane.showMessageDialog(null, "If you incorrectly log in 5 time, you will be blocked.", "Incorrect password!", 3);
                                txt_password.setText("");
                            }
                        }
                    } else {
                        this.txt_username.setText("");
                        txt_password.setText("");
                        String readfile = "";
                        readfile = this.readFile("incorrect_password");
                        this.writeFile("incorrect_password", "1" + readfile);
                        if (readfile.equals("1111")) {
                            this.disable_all_buttons();
                            db.close();
                        }
                        JOptionPane.showMessageDialog(null, "If you incorrectly log in 5 time, you will be blocked.", "Incorrect username!", 3);
                    }
                } catch (SQLException | FileNotFoundException | UnsupportedEncodingException ex) {
                    Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else {
                this.sms.setText("Password is invalid");
            }
        } else {
            this.sms.setText("Username is invalid");
        }
    }//GEN-LAST:event_btn_loginActionPerformed

    private void btn_cancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_cancelActionPerformed
        int i = JOptionPane.showConfirmDialog(null, "Are you sure to cancel?");
        if (i == JOptionPane.YES_OPTION) {
            System.exit(0);
        }

    }//GEN-LAST:event_btn_cancelActionPerformed

    private void rememberActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rememberActionPerformed
        check = true;
    }//GEN-LAST:event_rememberActionPerformed

    private void txt_usernameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_usernameActionPerformed
      
    }//GEN-LAST:event_txt_usernameActionPerformed

    private void txt_usernameMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txt_usernameMouseEntered
        // TODO add your handling code here:
        txt_password.getCursor();
    }//GEN-LAST:event_txt_usernameMouseEntered

    /**
     * @param args the command line arguments
     * @throws java.io.IOException
     */
    public static void main(String args[]) throws IOException {
        if (Login.readFile("incorrect_password").equals("11111")) {
            JOptionPane.showMessageDialog(null, "You have logged in incorrect 5 times.Please contact adminstator", "Unable to log in !", 2);

        } else if (!Login.readFile("remember").equals("")) {
            POS_Panel panel = new POS_Panel();
            panel.setVisible(true);

        } else {
            java.awt.EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    new Login().setVisible(true);
                }
            });
        }
    }

    public void disable_all_buttons() {
        this.btn_cancel.setEnabled(false);
        this.btn_login.setEnabled(false);
        this.txt_password.setEnabled(false);
        this.txt_username.setEnabled(false);;
        this.remember.setEnabled(false);
        this.sms.setText("Please contact adminstator !");
    }

    public static void signOut() {
        File f = new File("src/file/remember");
        f.delete();
    }

    public static void unlockUser() {
        File f = new File("src/file/incorrect_password");
        f.delete();
    }

    public static String readFile(String filename) throws IOException {
        String getText = "";
        String path = "src/file/" + filename;
        File f = new File(path);
        if (f.exists()) {
            try {
                BufferedReader br = new BufferedReader(new FileReader(path));
                getText = br.readLine();
                br.close();
            } catch (FileNotFoundException ex) {
                Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
         
            }
        }
        return getText;
    }

    public static void writeFile(String filename, String text) throws FileNotFoundException {
        String path = "src/file/" + filename;
        PrintWriter writer;
        try {
            writer = new PrintWriter(path, "UTF-8");
            writer.println(text);
            writer.close();
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void close() {
        WindowEvent winclose = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
        Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(winclose);
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel background;
    private javax.swing.JButton btn_cancel;
    private javax.swing.JButton btn_login;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JCheckBox remember;
    private javax.swing.JLabel sms;
    private javax.swing.JPasswordField txt_password;
    private javax.swing.JTextField txt_username;
    // End of variables declaration//GEN-END:variables
}
